package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.CluesPoolDO;
import com.qk.dto.clue.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.management.mapper.*;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: byLengs
 * @Date: 2025/10/13 17:42
 * @Description:
 */
@Service
@SuppressWarnings("all")
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;

    @Override
    public PageResult<CluesPoolDO> cluesPoolList(CluesPoolDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<CluesPoolDO> page = this.baseMapper.selectCluesPoolList(dto);
        return PageResult.<CluesPoolDO>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void toFalseClue(Integer id, FalseClueDTO dto) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.FAKE_CLUE);
        this.baseMapper.updateById(clue);
        ClueTrackRecord clueTrackRecord = new ClueTrackRecord();
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(id);
        clueTrackRecord.setType(ClueTrackRecordType.FALSE_CLUE);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        clueTrackRecord.setFalseReason(dto.getReason());
        clueTrackRecord.setRecord(dto.getRemark());
        clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.CONVERT_TO_BUSINESS);
        this.baseMapper.updateById(clue);
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setUserId(null);
        business.setClueId(id);
        this.businessMapper.insert(business);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if (dto.getStatus() == ClueStatusConstants.WAIT_FOLLOW_UP) {
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(clue);
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public ClueVO getClueInfoById(@PathVariable Integer id) {
        //获取线索基本信息
        Clue clue = this.baseMapper.selectById(id);
        //根据用户ID查询所属人姓名
        String name = this.userMapper.selectById(clue.getUserId()).getName();
        //根据线索ID查询线索跟进记录
        List<ClueTrackRecord> clueTrackRecords = this.clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId, id));
        //封装数据
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO recordVO = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            recordVO.setAssignName(name);
            return recordVO;
        }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;
    }

    @Override
    public PageResult<ClueDO> getByList(ClueListDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<ClueDO> page = this.baseMapper.selectByList(dto);
        return PageResult.<ClueDO>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addClue(ClueDTO dto) {
        if (ObjectUtil.isNull(dto.getPhone()) || ObjectUtil.isNull(dto.getChannel())) {
            throw new RuntimeException("手机号和渠道不能为空");
        }
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.baseMapper.insert(clue);
    }
}
